#include "transmit.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <arpa/inet.h>


int create_multicast_socket(struct sockaddr_in * dst, const char * dstAddr, int dstPort) {
    int fd = socket(AF_INET, SOCK_DGRAM, 0); // IPPROTO_UDP

    if (fd == -1) {
        fprintf(stderr, "Could not create socket\n");
        exit(-1);
    }

    /*sockaddr_in laddr;
    memset(&laddr, 0, sizeof(laddr));
    laddr.sin_family = AF_INET;
    laddr.sin_family.s_addr = htonl(INADDR_ANY);
    laddr.sin_port = INPORT_ANY;

    if (bind(fd, (socketaddr *) &laddr, sizeof(laddr)) != 0) {
        fprintf(stderr, "Could not bind socket\n");
        exit(-1);
    }*/



    struct in_addr localInterface;

    if (inet_aton("127.0.0.1", (in_addr *) &localInterface.s_addr) == 0) {
        fprintf(stderr, "Invalid local interface\n");
        exit(-1);
    }

    if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char *) &localInterface, sizeof(localInterface)) != 0) {
        fprintf(stderr, "Could not use multicast socket option\n");
        exit(-1);
    }




    memset(dst, 0, sizeof(dst));
    dst->sin_family = AF_INET;
    dst->sin_port = htons(dstPort);

    if (inet_aton(dstAddr, &dst->sin_addr) == 0) {
        fprintf(stderr, "Invalid destination address\n");
        exit(-1);
    }

    return fd;
}



int * create_datagram_sockets(unsigned int num) {
    int * socks = (int *) malloc(num * sizeof(int));

    if (!socks)
        return NULL;

    for (int i = 0; i < num; i++) {
        socks[i] = socket(PF_INET, SOCK_DGRAM, 0);

        if (socks[i] == -1) {
            fprintf(stderr, "Could not create datagram socket\n");
            perror("socket");
            //exit(-1);
            continue;
        }

        int broadcast = 1;

        if (setsockopt(socks[i], SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) == -1) {
            fprintf(stderr, "Could not set datagram socket options\n");
            perror("setsockopt");
            //exit(-1);
        }
    }

    return socks;
}
